/*
 * @Author: your name
 * @Date: 2020-06-29 10:16:50
 * @LastEditTime: 2020-07-06 18:42:03
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \im_web\src\store\actions\connect.js
 */
import store from '../'
import { Message } from 'iview'
import router from '../../router';
import { onSessions } from './session'
import util from '../../utils'

export function connect(loginInfo) {
    const nim = store.state.nim
    nim.connect().then(() => {
        console.log(loginInfo)
        let login = loginInfo.login;
        // let login = "momo"
        // let password = loginInfo.password;
        let password = '123456'
        return nim.loginBasic(login, password);
    }).then(ctrl => {
        console.log(ctrl)
        if (ctrl.code === 200) {
            let params = {
                uid: ctrl.params.user,
                sdktoken: ctrl.params.token
            }
            store.commit('updateUserUID', params)
            const me = nim.getMeTopic();
            // console.log(me)
            let onpres = {};
            me.onMetaDesc = function (meta) { console.log('connect-meta', meta) };
            me.onData = function (data) { console.log('connect-data', data) }
            me.onMeta = function (onMeta) {
                console.log('connect-onMeta', onMeta)
                console.log(onpres)
                if (onpres.act && !store.state.sessionMap[onpres.src]) {
                    onpres = []
                    store.commit('updateSessions', onMeta.sub.reverse())
                }
                if (onMeta.sub) {

                    // let oldSession = []
                    // store.commit('updateSessions', onMeta.sub.reverse())
                }
                if (onMeta.desc) {
                    onMeta.desc.avatar = util.makeImageUrl(onMeta.desc.public.photo)
                    store.commit("updateMyInfo", onMeta.desc)
                }

            }
            me.onAllMessagesReceived = function (onAllMessagesReceived) {
                console.log('connect-onAllMessagesReceived', onAllMessagesReceived)
            }
            me.onPres = function (data) {
                console.log("connect-onPres", data)
                if (data.act) {
                    console.log(1)
                    onpres = data
                    const nim = store.state.nim
                    const newsTopic = nim.getTopic(data.src)
                    if (!newsTopic.isSubscribed()) {
                        let getQuery = newsTopic.startMetaQuery().withLaterDesc().withLaterSub();
                        newsTopic.subscribe(getQuery.build(), data.src).then(ctrl => {
                            console.log(ctrl)
                            console.log('session--isSubscribed-->' + newsTopic.isSubscribed())
                        });
                    }
                    // store.commit('updateSessions', sessions.sub.reverse())
                }
                // if(data.act && data.what === "acs"){
                //     store.commit('updateSessions', res.sub.reverse())
                // }
            }
            me.onInfo = function (data) {
                console.log("connect--onInfo", data)
            }
            me.onMetaSub = function (data) {
                console.log("connect--onMetaSub", data)
            }
            me.onSubsUpdated = function (data) {
                console.log("connect--onSubsUpdated", data)

            }
            me.onDeleteTopic = function (data) {
                console.log("connect--onDeleteTopic", data)
            }
            me.subscribe(me.startMetaQuery().
                withLaterSub().
                withDesc().
                withTags().
                withCred().
                build()).catch(err => {
                    console.log(err)
                    nim.disconnect();
                }).finally(() => {
                    me.getMeta(me.startMetaQuery().withSub().build()).then(res => {
                        console.log('getMeta', res)
                        store.commit('updateSessions', res.sub.reverse())
                    }).catch(err => {
                        console.log(err.message)
                        console.log(err)
                        console.log(err.code)
                        if (err.message === "Timeout (504)") {
                            Message.error('获取记录超时！请重试')
                        }
                    });
                });
            // const fnd = nim.getFndTopic();
            // console.log(fnd.startMetaQuery().withSub().build())
            // console.log(me.getMeta(me.startMetaQuery().withSub().build()))
            // me.getMeta(me.startMetaQuery().withSub().build()).then(res => {
            //     console.log(res)
            // }).catch(err => {
            //     console.log(err.message)
            // });

            onSessions()
            // console.log(nim.newTopicWith('usrbhYegxPff6E'))
        }
    }).catch(err => {
        console.log('err', err)
        // nim.createAccountBasic(loginInfo.login, '123456').then(res => {
        //     console.log(res)
        // }).catch(err => {
        //     console.log(err)
        // })
        if (router.app._route.name === 'login' || router.app._route.name === "passport") {
            return
        }
        sessionStorage.clear();
        Message.error('连接出错！')
        router.push('/login');
    })
}
